package com.ydkfjs.common.interceptor;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ArrayUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ydkfjs.constants.LoginConstant;
import com.ydkfjs.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static cn.hutool.extra.servlet.ServletUtil.getClientIPByHeader;


/**
 * @Author: hb
 * @CreateTime: 2024-04-08 20:06
 * @Version: 1.0
 */
@Order(1)
@Slf4j
@Component
public class CollectorInterceptor implements HandlerInterceptor {

    private final IpUtils ipUtils;

    public CollectorInterceptor(IpUtils ipUtils) {
        this.ipUtils = ipUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("检测有用户操作");

        // 判断用户是否登录
        boolean login = StpUtil.isLogin();

        // 若用户未登录, 不更新
        if (!login) {
            return true;
        }

        // 获取用户id
        long loginIdAsLong = StpUtil.getLoginIdAsLong();

        log.info("用户id为: {}", loginIdAsLong);

        // 获取用户tokenSessioin,判断过期时间
        SaSession session = StpUtil.getTokenSession();
        long timeout = session.getTimeout();

        // 登录满一天,更新一次ip
        if (timeout < 60 * 60 * 24 * 7 - 60 * 60 * 24) {
            String ipAddr = ipUtils.getIpAddr(request);
            ipUtils.refreshIpDetailAsync(loginIdAsLong, ipAddr, LoginConstant.USER_LOGIN);
        }

        return true;
    }
}